using System;
using System.Reactive.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace Bull.Core.AttachedBehaviours
{
    public static class FocusManagerAttachedBehaviour
    {
        public static readonly DependencyProperty ControlToFocusProperty =
            DependencyProperty.RegisterAttached("ControlToFocus", typeof(IInputElement), typeof(FocusManagerAttachedBehaviour), new PropertyMetadata(null,
                (sender, e) =>
                {
                    var element = e.NewValue as Control;
                    if (element == null)
                        return;
                    Observable.FromEventPattern<RoutedEventHandler, RoutedEventArgs>(
                        handler => element.Loaded+=handler,
                        handler => element.Loaded -= handler
                    ).Subscribe(result => Keyboard.Focus(element));
                }));

        
        public static void SetControlToFocus(Control sender, Control value)
        {
            sender.SetValue(ControlToFocusProperty, value);
        }

        public static Control GetControlToFocus(Control sender)
        {
            return (Control)sender.GetValue(ControlToFocusProperty);
        }
    }
}